<?php
/**
 * Created by PhpStorm.
 * User: silenceper
 * Date: 2016/11/24
 * Time: 下午2:00
 */

namespace common\repositories\myhtsq;


use common\entities\myhtsq\ProjectContactEntity;
use common\repositories\BaseRepository;
use common\support\StringHelper;

/**
 * Class ProjectContactRepository
 * @package common\repositories\myhtsq
 */
class ProjectContactRepository extends BaseRepository
{
    /**
     * 获取交付人信息
     * @param $orgId
     * @param $projectId
     * @param array $userType
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getList($orgId, $projectId, $userType = [])
    {
        $query = ProjectContactEntity::find();
        $query->where(["org_id" => $orgId, "project_id" => $projectId]);
        $query->andFilterWhere(["user_type" => $userType]);
        return $query->asArray()
            ->all();
    }

    /**
     * 根据项目删除
     * @param $orgId
     * @param array $projectIds
     * @param null $userType 可选
     * @return int
     */
    public function deleteByProject($orgId, $projectIds = [], $userType = null)
    {
        if (empty($projectIds) || empty($orgId)) {
            return false;
        }
        $condition = ["org_id" => $orgId, "project_id" => $projectIds];
        if (!empty($userType)) {
            $condition["user_type"] = $userType;
        }
        return ProjectContactEntity::deleteAll($condition);
    }

    /**
     * 增加联系人,如果存在则更新。
     * @param $data
     * @return bool
     */
    public function addContact($data)
    {
        $entity = ProjectContactEntity::find()
            ->where([
                'org_id' => $data['org_id'],
                'project_id' => $data['project_id'],
                'user_guid' => $data['user_guid'],
                'user_type' => $data['user_type'],
            ])
            ->one();

        if (empty($entity)) {
            $entity = new ProjectContactEntity();
            $entity->id = StringHelper::uuid();
        }

        $entity->setAttributes($data);
        $entity->updated_at = date("Y-m-d H:i:s");
        $entity->created_at = date("Y-m-d H:i:s");

        return $entity->save();
    }
}